<?php

namespace Hlcreation\Basic;
use Illuminate\Http\Request;
use App\Services\Pay\PayServer;
use Illuminate\Support\Facades\Storage;

class Helper
{

    /** get post 传参
     * @param $param
     * @param string $v
     * @return string
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public static function getPost($param, $v = "")
    {
        $request = app()->make(Request::class);
        $res = $request->get($param,$v) ?  $request->get($param,$v) : $request->post($param,$v);
        return  is_array($res) ? $res : trim($res);
    }

    /** 返回加密密码
     * @param $pwd
     * @return string
     */
    public static function returnPwd($pwd, $halt){
        return md5(sha1(md5($pwd).$halt));
    }

    public static function returnToken($id){
        return md5(sha1(md5($id).time()));
    }

    /**
     * json返回
     * @param string $msg 返回信息
     * @param array $data 返回数据
     * @param int $code 状态码  200 成功 400 失败
     */
    public static function toJson( $msg = '', $code = 200, $data = [])
    {
        $json = compact('msg','data','code');

        return json_encode($json,JSON_UNESCAPED_SLASHES);
    }

    public static function orderNo(){
        return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    // curl  Post 请求
    public static function httpPost($url,$data,$type='post',$res="json"){

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSLVERSION, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //2.设置curl的参数
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);   //过滤ssl验证
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,2);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if ($type == "post"){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }

        //3.采集
        $output = curl_exec($curl);

        //4.关闭
        curl_close($curl);

        return $res == "json" ? json_decode($output,true) : $output;
    }


    //递归遍历 完成方式 根据pid 把对应id下面的pid数据重新排序
    public static function sortDg(&$arr, $pid = 0)
    {
        //首先要确定递归的终止条件
        $result = [];
        foreach ($arr as $k => $item) {
            //dump($item);die();
            if ($pid == 0 && $item['pid'] == 0) {
                $result[$item['id']] = $item;
                $result[$item['id']]['child'][] = sort_dg($arr, $item['id']);

            } else {
                if ($item['pid'] == $pid) {
                    $result[$item['id']] = $item;
                    $result[$item['id']]['child'][] = sort_dg($arr, $item['id']);
                } else {
                    continue;
                }
            }
        }
        return $result;
    }
    /**
     * 上传路径转化,默认路径
     * @param $path
     * @param int $type
     * @param bool $force
     * @return string
     */

    public static function makePath($path, int $type = 2, bool $force = false)
    {
        $path = '/' . ltrim(rtrim($path));

        switch ($type) {
            case 1:
                $path .= '/' . date('Y');
                break;
            case 2:
                $path .= '/' . date('Y') . '/' . date('m');
                break;
            case 3:
                $path .= '/' . date('Y') . '/' . date('m') . '/' . date('d');
                break;
        }

        try {
            if (is_dir(base_path() . 'public' . '/' . 'uploads' . $path) == true || mkdir(base_path() . 'public' . '/' . 'uploads' . $path, 0777, true) == true) {
                return trim(str_replace('/', '/', $path), '.');
            } else return '';
        } catch (\Exception $e) {
            if ($force)
                throw new \Exception($e->getMessage());
            return '无法创建文件夹，请检查您的上传目录权限：' . base_path() . 'public' . '/' . 'uploads' . '/' . 'attach' . '/';
        }

    }
    public static function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
    //32位随机字符串
    public static function createNonceStr($length = 32)
    {
        $str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $key = "";
        for ($i = 0; $i < $length; $i++) {
            $key .= $str{mt_rand(0, 32)};     //生成php随机数
        }
        return $key;
    }
    //对象转数组
    public static function objectToArray($obj) {
        return is_object($obj) ? json_decode(json_encode($obj), true) : $obj;
    }

    // 并且创建
    public static function checkDir($dir){
        if (!is_dir($dir)) { mkdir($dir,0777,true);   }
    }


    /** 单文件上传
     * @param $name  文件key名
     * @param int $uid  用户id
     * @param string $dir 要存放的目录
     * @return mixed
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public static function uploads($name, $uid = 0, $dir = 'contract'){
        $request = app()->make(Request::class);
        //获取上传的文件
        $file=$request->file($name);
        if (!$file) {return false;}
        //获取上传文件的文件名
        $filename=$file->getClientOriginalName();
        //获取上传文件的后缀
        $fileextension=$file->getClientOriginalExtension();
        //获取上传文件的大小
        $filesize=$file->getClientSize();
        //获取缓存在tmp目录下的文件名
        $data['name']=$file->getFilename();
        //获取上传的文件缓存在tmp文件夹下的绝对路径
        $realpath=$file->getRealPath();

        $times = date('Ymd');
        $new_dir = "upload/".$uid."/".$dir."/".$times;
        self::checkDir($new_dir);
        //将缓存在tmp目录下的文件移到某个位置，返回的是这个文件移动过后的路径
        $path = $_SERVER['DOCUMENT_ROOT']."/upload/".$uid."/".$dir."/".$times;

        $name =self::getMillisecond().'.'.$fileextension;

        $path=$file->move($path,$name);
        $data['filename'] = $name;
        $data['src'] = $new_dir.'/'.$path->getFilename();
        $data['prefix'] =  $fileextension;
        return $data;
    }


    /** 微信校验文件上传
     * @param $name  文件key名
     * @param int $uid  用户id
     * @param string $dir 要存放的目录
     * @return mixed
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public static function checkFileUploads($name){
        $request = app()->make(Request::class);
        //获取上传的文件
        $file=$request->file($name);
        if (!$file) {return false;}
        //获取上传文件的文件名
        $filename=$file->getClientOriginalName();
        //获取上传文件的后缀
        $fileextension=$file->getClientOriginalExtension();
        //获取上传文件的大小
        $filesize=$file->getClientSize();
        //获取缓存在tmp目录下的文件名
        $name = $file->getFilename();

        //获取上传的文件缓存在tmp文件夹下的绝对路径
        $realpath=$file->getRealPath();

        $times = date('Ymd');
        //将缓存在tmp目录下的文件移到某个位置，返回的是这个文件移动过后的路径
        $path = $_SERVER['DOCUMENT_ROOT']."/";

        if ($file == "robots.txt") {
            return ['code'=>400];
        }
        $file->move($path,$filename);
        return ['code'=>200, 'name'=>$filename];
    }

    public static function GetRandStr($length){
        $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }




    public  static function arrayToXml($arr){
        $model = new PayServer();
        $xml = "<xml>";
        foreach ($arr as $key=>$val){
            if(is_array($val)){
                $xml.="<".$key.">".$model->arrayToXml($val)."</".$key.">";
            }else{
                $xml.="<".$key.">".$val."</".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    public  static function xmlToArray($xml,$type='')
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        //simplexml_load_string()解析读取xml数据，然后转成json格式
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($type == "json") {
            $json = json_encode($xmlstring);
            return $json;
        }
        $arr = json_decode(json_encode($xmlstring), true);
        return $arr;
    }


    /**
     * [将Base64图片转换为本地图片并保存]
     * @E-mial wuliqiang_aa@163.com
     * @TIME   2017-04-07
     * @WEB    http://blog.iinu.com.cn
     * @param  [Base64] $base64_image_content [要保存的Base64]
     * @param  [目录] $path [要保存的路径]
     */
    public static function base64_image_content($base64_image_content,$path = 'upload/contract/png/')
    {
        //匹配出图片的格式
        if (strstr($base64_image_content,",")){
            $image = explode(',',$base64_image_content);
            $images = $image[1];
            self::checkDir($path);
            $file_name = time() . ".jpg";
            $new_file = $_SERVER['DOCUMENT_ROOT']."/".$path . $file_name;
            if (file_put_contents($new_file, base64_decode($images))) {
                return  $path. $file_name;
            } else {
                return false;
            }
        }
        return false;

    }

    /** 图片转换为base64
     * @param $img_file
     * @return string
     */
    public static function imgToBase64($img_file) {

        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限

            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }

                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

            }
            fclose($fp);
        }

        return $img_base64; //返回图片的base64
    }



    public static function is_mobile($mobile)
    {
        if(empty($mobile)) return false;

        $eg = '/^((13[0-9])|(16[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,1,2,3,5-8])|(18[0-9])|166|198|199)\d{8}$/';

        if(preg_match($eg, $mobile)){

            return true;
        }else{
            return false;

        }
    }


    /**
     * 数组转字符串去重复
     * @param array $data
     * @return false|string[]
     */
    public static function unique(array $data)
    {
        return array_unique(explode(',', implode(',', $data)));
    }


    /***
     *
     *  单图上传
     *
     * */
    public static function uploadImg($file){
        $originalName = $file->getClientOriginalName();

        //扩展名
        $ext = $file->getClientOriginalExtension();
        //MimeType
        $type = $file->getClientMimeType();
        //临时绝对路径
        $realPath = $file->getRealPath();

        $filename = uniqid().'.'.$ext;

        $bool = Storage::disk('uploads')->put($filename,file_get_contents($realPath));
        //判断是否上传成功
        if($bool){
            $path = asset('img'.'/'.date('Ymd').'/'.$filename);
            $path = str_replace("http", "https", $path);
            return $path;
        }else{
            return false;
        }
    }


}




